﻿using ManagementApi.Services.Authentication;
using Modules;
using Modules.Corp;
using Modules.Project;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Entity;
using PmSoft.Exceptions;

namespace ManagementApi.Mvc
{
    public class CurrentProjectCorpStateProvider : IApplicationContextStateProvider
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public CurrentProjectCorpStateProvider(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public string Name => "CurrentProjectCorp";

        IProjectCorp? _currentCorp;

        public Func<ApplicationContext, T?> Get<T>()
        {
            return context =>
            {
                if (_currentCorp != null)
                {
                    return (T)_currentCorp;
                }

                var authenticationService = _httpContextAccessor.GetService<UserAuthenticationService>();
                if (authenticationService == null)
                    throw new ArgumentNullException(nameof(authenticationService));

                var user = authenticationService.GetLoginUser();
                if (user is not CorpInfo corpInfo)
                    throw new BusinessException("当前登陆非企业用户");

                var projectCorpService = _httpContextAccessor.GetService<ProjectCorpService>();
                if (projectCorpService == null)
                    throw new ArgumentNullException(nameof(projectCorpService));

                var projectCorps = projectCorpService.GetProjectCorpsByProjectId(corpInfo.ProjectId);

                var projectCorp = projectCorps.FirstOrDefault(m => m.CorpId == corpInfo.CorpId);
                if (projectCorp == null)
                {
                    //throw new ArgumentNullException(nameof(projectCorp));
                }
                return (T?)(projectCorp as IProjectCorp);

            };
        }
    }
}